<template>
  <div class="image-file-preview">
    <!-- 图片 -->
    <template v-if="preview.fileFormat === 'image'">
      <el-image :src="preview.temporaryUrl" :preview-src-list="[preview.temporaryUrl]" style="display:none" ref="image"/>
    </template>
    <!-- pdf -->
    <template v-else-if="preview.fileFormat === 'pdf'">
      <el-dialog width="80%" :title="preview.fileName" :visible.sync="preview.open" append-to-body fullscreen destroy-on-close>
        <div v-loading="preview.loading" :style="'height:'+ preview.height">
          <iframe
            :src="preview.temporaryUrl"
            style="width: 100%;height: 100%"
            rameborder="no"
            border="0"
            marginWidth="0"
            marginHeight="0"
            scrolling="no"
            allowtransparency="yes"
            frameborder="no"
          />
        </div>
      </el-dialog>
    </template>
    <!-- doc -->
    <template v-else-if="preview.fileFormat === 'doc'">
      <el-dialog
        width="80%"
        :title="preview.fileName"
        :visible.sync="preview.open"
        append-to-body
        fullscreen
        destroy-on-close
      >
        <!-- 预览文件的地方（用于渲染） -->
        <div ref="file"></div>
      </el-dialog>
    </template>
    <!-- excel -->
    <template v-else-if="preview.fileFormat === 'excel'">
      <el-dialog
        custom-class="custom-class-excel"
        :title="preview.fileName"
        :visible.sync="preview.open"
        append-to-body
        fullscreen
        destroy-on-close
      >
        <!-- 预览文件的地方（用于渲染） -->
        <div id="luckysheet" style="margin: 0;padding: 0;position: absolute;width: 100%;left: 0;top: 30px;bottom: 0;"></div>
      </el-dialog>
    </template>
  </div>
</template>
<script>
const imageSuffix = ['gif', 'jpg', 'jpeg', 'png']
const pdfSuffix = ['pdf']
const docSuffix = ['doc', 'docx']
const excelSuffix = ['xls', 'xlsx']
import { get_url_extension, asynLoad } from '@/utils/zito'
import request from '@/utils/request'

let docx = require('docx-preview')
import LuckyExcel from 'luckyexcel'

export default {
  name: 'imageFilePreview',
  components: {},
  data() {
    return {
      preview: {
        open: false,
        fileName: undefined,
        fileFormat: undefined,
        temporaryUrl: undefined,
        height: document.documentElement.clientHeight - 94.5 + 'px;'
      },
      luckysheet: undefined
    }
  },
  computed: {},
  methods: {
    openPreview(item) {
      console.log(item)
      this.preview.temporaryUrl = item.temporaryUrl
      this.preview.fileName = item.fileName
      this.preview.fileFormat = imageSuffix.includes(item.fileFormat || get_url_extension(item.temporaryUrl))
        ? 'image' : pdfSuffix.includes(item.fileFormat || get_url_extension(item.temporaryUrl))
          ? 'pdf' : docSuffix.includes(item.fileFormat || get_url_extension(item.temporaryUrl))
            ? 'doc' : excelSuffix.includes(item.fileFormat || get_url_extension(item.temporaryUrl))
              ? 'excel' : ''
      if (this.preview.fileFormat === 'image') {
        this.$nextTick(() => {
          this.$refs.image.clickHandler()
        })
      } else if (this.preview.fileFormat === 'pdf') {
        this.preview.open = true
      } else if (this.preview.fileFormat === 'doc') {
        this.preview.open = true
        request({
          method: 'get',
          responseType: 'blob',
          url: this.preview.temporaryUrl // 自己的服务器，提供的一个word下载文件接口
        }).then((data) => {
          docx.renderAsync(data, this.$refs.file) // 渲染到页面
        })
      } else if (this.preview.fileFormat === 'excel') {
        this.preview.open = true
        this.loadPlugins()
      }
    },
    loadPlugins() {
      const baseURL = '//cdn.jsdelivr.net/npm/luckysheet@latest/dist'
      Promise.all([
        asynLoad(`${baseURL}/plugins/css/pluginsCss.css`, true),
        asynLoad(`${baseURL}/plugins/plugins.css`, true),
        asynLoad(`${baseURL}/css/luckysheet.css`, true),
        asynLoad(`${baseURL}/assets/iconfont/iconfont.css`, true),
        asynLoad(`${baseURL}/plugins/js/plugin.js`),
        asynLoad(`${baseURL}/luckysheet.umd.js`)
      ])
        .then(() => {
          this.luckysheet = window.luckysheet
          this.getOriginFile() // 获取远端文件
        })
        .catch(res => {
        })
    },
    getOriginFile() {
      request({
        method: 'get',
        responseType: 'blob',
        //请求头，要自己写
        //excel文件路径
        url: this.preview.temporaryUrl
      }).then(data => {
        const blob = new Blob([data])
        const file = new File([blob], this.preview.fileName)
        this.init(file) // 开始渲染
      }).catch(e => {
      }).finally(() => {
      })
    },
    // 渲染方法，接受文件对象，如果是本地文件直接传入文件即可
    init(file) {
      this.luckysheet.destroy() // 先销毁当前容器
      LuckyExcel.transformExcelToLucky(file, exportJson => {
        if (exportJson.sheets === null || !exportJson.sheets.length) {
          this.$message.error('无法读取excel文件的内容,当前不支持xls文件!')
          return
        }
        this.luckysheet.create({
          container: 'luckysheet',
          showinfobar: false,
          lang: 'zh',
          data: exportJson.sheets,
          title: exportJson.info.name,
          userInfo: exportJson.info.name.creator
        })
      })
    }
  }
}
</script>

<style lang="scss">
#luckysheet-wa-editor {
  height: 0px;
  padding: 0;
  position: static;
  border: 0px;
}

#luckysheet-wa-calculate {
  height: 0px;
  position: static;
  border: 0px;
}

.custom-class-excel {
  .el-dialog__body {
    position: relative;
    height: calc(100% - 55px);
  }
}
</style>
